//
//  SMSLoginVC.m
//  MovieDate
//
//  Created by yyta on 16/4/1.
//  Copyright © 2016年 MovieDate. All rights reserved.
//

#import "SMSLoginVC.h"
#import "RegisterVC.h"
#import "AppDelegate.h"

@interface SMSLoginVC ()  <UITextFieldDelegate> {
    BOOL boolSendPhoneCode;
    NSMutableDictionary *dictNext;
    
    BOOL isRegin;
}

@property (weak, nonatomic) IBOutlet UIButton *pBtnSendPhoneCode;
@property (weak, nonatomic) IBOutlet UIButton *pBtnNext;

@property (weak, nonatomic) IBOutlet UITextField *pTxtPhone;
@property (weak, nonatomic) IBOutlet UITextField *pTxtPhoneCode;


@end

@implementation SMSLoginVC

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = NO;
}

- (void)initInfo {
    [super initInfo];
    
//    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
//    if (![userDefaults boolForKey:@"StartPage"]) {
//        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Login" bundle:nil];
//        UIViewController *vc = [storyboard instantiateViewControllerWithIdentifier:@"StartPageVC"];
//        [self presentViewController:vc animated:NO completion:^{}];
//    }
    
    dictNext = [NSMutableDictionary dictionary];
    self.navigationController.navigationBar.barTintColor = [UIColor whiteColor];
    
    NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:[UIColor blackColor], NSForegroundColorAttributeName, [UIFont boldSystemFontOfSize:20], NSFontAttributeName, nil];
    [self.navigationController.navigationBar setTitleTextAttributes:attributes];
    self.title = @"注册或登录";
    [self selLoadData];
}

- (void)selLoadData
{
    NSString *str = [[NSUserDefaults standardUserDefaults] objectForKey:@"myToken"];
    if (str && str.length > 2)
    {
        [SVProgressHUD show];
        [TDNetwork requestActivate:[[NSUserDefaults standardUserDefaults] objectForKey:@"myToken"] complete:^(BOOL succeed, NSString *ret, NSDictionary *dictionary) {
            [SVProgressHUD dismiss];
            if (succeed) {
                UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
                UIViewController *tabbar = [storyBoard instantiateInitialViewController];
                [self.navigationController presentViewController:tabbar animated:NO completion:nil];

                UIApplication *app = [UIApplication sharedApplication];
                AppDelegate *appDelegate = app.delegate;
                [appDelegate selCloseNoti];
            }
        }];
    }
}

- (IBAction)btnUserRegisterAction:(id)sender {
    [TDNetwork testDynCodePostURL:testCodeIP andPhoneNumber:self.pTxtPhone.text andCode:self.pTxtPhoneCode.text complete:^(BOOL succeed, NSString *ret, NSDictionary *dictionary) {
        if (succeed) {
            
            switch ([ret intValue]) {
                case 1:
                    [dictNext setValue:[dictionary valueForKey:@"res"] forKey:@"phoneCode"];
                    [SVProgressHUD dismiss];
                    [self performSegueWithIdentifier:@"idfRegisterVC" sender:nil];
                    break;
                    
                case -1:
                    [SVProgressHUD showErrorWithStatus:@"账号已经注册"];
                    
                    break;
                case -2:
                    [SVProgressHUD showErrorWithStatus:@"验证码不正确"];
                    
                    break;
                    
                case -3:
                    [SVProgressHUD showErrorWithStatus:@"验证码超过3分钟"];
                    
                    
                    break;
                case -4:
                    [SVProgressHUD showErrorWithStatus:@"手机号或者验证码（为空）不正确"];
                    
                    
                    break;
                default:
                    [SVProgressHUD showErrorWithStatus:@""];
                    break;
            }
        }else{
            [SVProgressHUD showErrorWithStatus:@"网络请求失败"];
        }
    }];
}

- (IBAction)btnUserLoginAction:(id)sender
{
    __weak typeof(self) weakSelf = self;
    if (!isRegin) {
        NSString *identifierForVendor = [[NSUserDefaults standardUserDefaults] objectForKey:MACROS_KEY_DEVICE_TOKEN];
        [TDNetwork loginPostURLPhoneCode:loginIPPhone andphoneNumber:self.pTxtPhone.text andCode:self.pTxtPhoneCode.text andType:@"2" andMac:@"" andImsi:@"" andSystemName:@"" andSystemVersion:@"" andDeviceToke:identifierForVendor?identifierForVendor:self.pTxtPhone.text andDeviceType:@"2" complete:^(BOOL succeed, NSString *ret, NSDictionary *dictionary) {
            UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
            UIViewController *tabbar = [storyBoard instantiateInitialViewController];
            if (succeed)
            {
                switch ([ret intValue])
                {
                    case 1:
                    {
                        NSLog(@"%@", dictionary);
                        NSString * strToken = [dictionary objectForKey:@"token"];
                        [[NSUserDefaults standardUserDefaults] setValue:strToken forKey:@"myToken"];
                        [SVProgressHUD showSuccessWithStatus:@"登录成功"];
                        [self.navigationController presentViewController:tabbar animated:NO completion:nil];
                    }
                        break;
                        
                    case -1:
                        [SVProgressHUD showErrorWithStatus:@"手机号或者密码不正确"];
                        break;
                        
                    case -2:
                        [SVProgressHUD showErrorWithStatus:@"账户已冻结"];
                        break;
                        
                    case -3:
                        [SVProgressHUD showErrorWithStatus:@"验证次数太多，稍后再试"];
                        break;
                        
                    default:
                        [SVProgressHUD showErrorWithStatus:@"未知错误"];
                        break;
                }
                
                UIApplication *app = [UIApplication sharedApplication];
                AppDelegate *appDelegate = app.delegate;
                [appDelegate selCloseNoti];
            } else {
                [SVProgressHUD showErrorWithStatus:@"网络请求失败"];
            }
        }];
    } else {
        [TDNetwork testDynCodePostURL:testCodeIP andPhoneNumber:self.pTxtPhone.text andCode:self.pTxtPhoneCode.text complete:^(BOOL succeed, NSString *ret, NSDictionary *dictionary) {
            if (succeed) {
                
                switch ([ret intValue]) {
                    case 1:
                        dictNext = [@{@"phoneCode":[dictionary valueForKey:@"res"],@"phone":weakSelf.pTxtPhone.text} mutableCopy];
                        [SVProgressHUD dismiss];
                        [self performSegueWithIdentifier:@"idfRegisterDirectVC" sender:nil];
                        break;
                        
                    case -1:
                        [SVProgressHUD showErrorWithStatus:@"账号已经注册"];
                        
                        break;
                    case -2:
                        [SVProgressHUD showErrorWithStatus:@"验证码不正确"];
                        
                        break;
                        
                    case -3:
                        [SVProgressHUD showErrorWithStatus:@"验证码超过3分钟"];
                        
                        
                        break;
                    case -4:
                        [SVProgressHUD showErrorWithStatus:@"手机号或者验证码（为空）不正确"];
                        
                        
                        break;
                    default:
                        [SVProgressHUD showErrorWithStatus:@""];
                        break;
                }
            }else{
                [SVProgressHUD showErrorWithStatus:@"网络请求失败"];
            }
        }];
    }

}

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:@"idfRegisterDirectVC"]) {
        RegisterVC *nextVC = segue.destinationViewController;
        nextVC.pDictInfo = dictNext;
    }
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}

- (IBAction)btnProtcolAction:(id)sender {
    [self performSegueWithIdentifier:@"idfProtcolVC" sender:nil];
}

- (IBAction)btnRegisterAction:(UIButton *)sender {
    [self performSegueWithIdentifier:@"idfPhoneAndPassword" sender:nil];
}

- (IBAction)setPBtnSendPhoneCodeAction:(UIButton *)pBtnSendPhoneCode
{
    if ([self selMobileUseful:self.pTxtPhone.text].length != 11) {
        return;
    }
    [dictNext setValue:self.pTxtPhone.text forKey:@"phone"];
    
    [TDNetwork sendDynCodePostURL:sendDynCodeIP andPhoneNumber:self.pTxtPhone.text andType:!isRegin?@"2":@"1" complete:^(BOOL succeed, NSString *ret, NSDictionary *dictionary) {
        if ([ret isEqualToString:@"1"]) {
            boolSendPhoneCode = YES;
            
            pBtnSendPhoneCode.backgroundColor = [UIColor grayColor];
            __block int timeout = 59; //倒计时时间
            dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
            dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
            dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
            dispatch_source_set_event_handler(_timer, ^{
                if(timeout<=0){ //倒计时结束，关闭
                    dispatch_source_cancel(_timer);
                    dispatch_async(dispatch_get_main_queue(), ^{
                        //设置界面的按钮显示 根据自己需求设置
                        [pBtnSendPhoneCode setTitle:@"获取验证码" forState:UIControlStateNormal];
                        pBtnSendPhoneCode.backgroundColor = [UIColor colorWithRed:255.0/255 green:198.0/255 blue:88.0/255 alpha:1];
                        pBtnSendPhoneCode.userInteractionEnabled = YES;
                    });
                }else{
                    int seconds = timeout % 60;
                    NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];
                    dispatch_async(dispatch_get_main_queue(), ^{
                        
                        //设置界面的按钮显示 根据自己需求设置
                        [UIView beginAnimations:nil context:nil];
                        [UIView setAnimationDuration:1];
                        pBtnSendPhoneCode.titleLabel.text = [NSString stringWithFormat:@"%@秒重新发送",strTime];
                        [pBtnSendPhoneCode setTitle:[NSString stringWithFormat:@"%@秒重新发送",strTime] forState:UIControlStateNormal];
                        [UIView commitAnimations];
                        
                        pBtnSendPhoneCode.userInteractionEnabled = NO;
                    });
                    timeout--;
                }
            });
            dispatch_resume(_timer);
            
        } else if([ret isEqualToString:@"2"]) {
            isRegin = YES;
            [self setPBtnSendPhoneCodeAction:pBtnSendPhoneCode];
        } else {
            [SVProgressHUD showInfoWithStatus:@"发送失败"];
        }
    }];
    
    
    
}

//判断是否是手机号
- (NSString *)selMobileUseful:(NSString *)mobile
{
    if (mobile.length < 11)
    {
        [SVProgressHUD showErrorWithStatus:@"请输入有效手机号码"];
        return @"";
    }else{
        NSString *CM_NUM = @"1[0-9]{10}$";
        
        NSPredicate *pred1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM_NUM];
        BOOL isMatch1 = [pred1 evaluateWithObject:mobile];
        
        if (isMatch1) {
            return mobile;
        } else {
            [SVProgressHUD showErrorWithStatus:@"请输入有效手机号码"];
            return @"";
        }
    }
    return nil;
}


#pragma mark - UITextFieldDelegate

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if ([string isEqualToString:@""]) {
        if (textField.text.length <= 11) {
            [_pBtnSendPhoneCode setEnabled:NO];
            [_pBtnSendPhoneCode setBackgroundColor:[UIColor colorWithRed:180/255.0f green:179/255.0f blue:175/255.0f alpha:1]];
        }
        
        return YES;
    }
    
    if (textField.tag == 1201) {
        if (textField.text.length == 10) {
            [_pBtnSendPhoneCode setBackgroundColor:[UIColor colorWithRed:253/255.0f green:177/255.0f blue:53/255.0f alpha:1]];
            [_pBtnSendPhoneCode setEnabled:YES];
        } else if (textField.text.length == 11) {
            [_pBtnSendPhoneCode setBackgroundColor:[UIColor colorWithRed:253/255.0f green:177/255.0f blue:53/255.0f alpha:1]];
            [_pBtnSendPhoneCode setEnabled:YES];
            return NO;
        } else {
            [_pBtnSendPhoneCode setBackgroundColor:[UIColor colorWithRed:180/255.0f green:179/255.0f blue:175/255.0f alpha:1]];
            [_pBtnSendPhoneCode setEnabled:NO];
        }
        
    }
    
    if (textField.text.length > 0 && boolSendPhoneCode && _pTxtPhone.text.length > 0) {
        [_pBtnNext setBackgroundColor:[UIColor colorWithRed:253/255.0f green:177/255.0f blue:53/255.0f alpha:1]];
        [_pBtnNext setEnabled:YES];
    } else {
        [_pBtnNext setBackgroundColor:[UIColor colorWithRed:180/255.0f green:179/255.0f blue:175/255.0f alpha:1]];
        [_pBtnNext setEnabled:NO];
    }
    
    return YES;
}

@end
